package com.ky.pro.java.concurrency;

import com.ky.pro.java.concurrency.algo.FiboUtil;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @ClassName CyclicBarrierMain
 * @Description 使用CyclicBarrier实现
 * @Date 2021/11/27 9:58
 * @Author kevin
 **/
public class CyclicBarrierMain {

    public static void main(String[] args) {
        long start = System.currentTimeMillis();

        // 在这里创建一个线程或线程池，
        // 异步执行 下面方法

        CyclicBarrier barrier = new CyclicBarrier(2);

        FiboCyclicBarrierTask task = new FiboCyclicBarrierTask(barrier);
        new Thread(task).start();

        try {
            barrier.await();
            // 确保  拿到result 并输出
            System.out.println("异步计算结果为：" + task.getResult());

            System.out.println("使用时间：" + (System.currentTimeMillis() - start) + " ms");
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 然后退出main线程
    }

    static class FiboCyclicBarrierTask implements Runnable {

        private CyclicBarrier barrier;

        int result;

        FiboCyclicBarrierTask(CyclicBarrier barrier) {
            this.barrier = barrier;
        }

        @Override
        public void run() {
            result = FiboUtil.fibo(36);
            try {
                barrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }

        public int getResult() {
            return result;
        }
    }

}
